﻿using System;

using OctoOS.UI;
using OctoOS;

public partial class __category : OOSPage
{
	class PathInfo
	{
		[PathInfoMember(0)]
		[RangeValidator(0, Int64.MaxValue)]
		[IntegerBase(64)]
		internal long CategoryID = 0;

		[PathInfoMember(1)]
		internal string Title = "";

		[PathInfoMember(2, true)]
		internal int PageIndex = 0;

		void PostInit()
		{
			if(PageIndex > 0)
				PageIndex--;
		}
	}

	PathInfo _pathInfo;
	int _artOnPage = 20;

	protected void Page_Init(object sender, EventArgs e)
	{
		_pathInfo = EnablePathInfo<PathInfo>();
	}

    protected void Page_Load(object sender, EventArgs e)
    {
		AddBreadcrumb(string.Empty, "/");

		var resourceInfo = AppUtil.GetResourceInfo(OOSRequest.Current);
		var settings = resourceInfo.Settings;
		var categories = resourceInfo.Categories;
		var currentCategory = AppUtil.GetCategory(categories, _pathInfo.CategoryID);

		if(!String.Equals(_pathInfo.Title, AppUtil.GetEncodedTitle(currentCategory.Title), StringComparison.OrdinalIgnoreCase))
			Response.RedirectPermanent(Urls.GetCategory(_pathInfo.CategoryID, currentCategory.Title));

		PageTitle = currentCategory.Title;

		if(settings.FeedMode != FeedMode.None)
		{
			Commands.AddCommand(new Command
			{
				Icon = "/images/rss.gif",
				HRef = Urls.Ajax.GetCategoryRss(_pathInfo.CategoryID, true)
			});
		}
		
		int startIndex = _pathInfo.PageIndex * _artOnPage;
		int totalCount;
		CategoryArticlePreview[] featuredArticles;
		CategoryArticlePreview[] notFeaturedArticles;

		ApiService.GetCategoryArticles(OOSRequest.Current, 
			_pathInfo.CategoryID, startIndex, _artOnPage, out featuredArticles, out notFeaturedArticles, out totalCount);

		foreach(var featuredArticle in featuredArticles)
			featuredArticlesList.Items.AddItem(new CategoryArticleUIPreview(featuredArticle));

		if(notFeaturedArticles.Length == 0)
		{
			empty.Visible = true;
			empty.SetContent(Resources.Main.shared_NoArticlesMessage);
		}
		else
		{
			foreach(var preview in notFeaturedArticles)
				articlesList.Items.AddItem(new CategoryArticleUIPreview(preview));

			myPager.PageCount = NumericPager.CalculatePageCount(totalCount, _artOnPage);
			myPager.SelectedIndex = _pathInfo.PageIndex;
			myPager.FirstPageUrl = Urls.GetCategory(_pathInfo.CategoryID, _pathInfo.Title);
			myPager.PageUrlPattern = Urls.GetCategory(_pathInfo.CategoryID, _pathInfo.Title) + "/{0}";
		}
    }
}